// 配置信息
import { defineStore } from "pinia"
import { apiGetShopCartList, deleteBatch } from '@/api/shopping-cart.js'
import { showToast } from '@/utils/common.js'

let useCartStore = defineStore("cart", {
	state: () => {
		return {
			list: [],
			selectedIds: new Set(), // 选中的商品ID集合
			isLoading: false,
			isDeleteLoading: true,
			error: null
		}
	},
	getters: {
		// 计算单个商品的小计
		getSubtotal: (state) => (item) => {
			return (item.productSpec.price * item.number).toFixed(2);
		},
		// 计算购物车总价
		totalPrice: (state) => {
			return state.list
				.filter(item => state.selectedIds.has(item.id))
				.reduce((total, item) => total + (item.productSpec.price * item.number), 0)
				.toFixed(2);
		},
		// 判断是否全选
		isAllSelected: (state) => {
			return state.list.length > 0 &&
				state.list.every(item => state.selectedIds.has(item.id));
		},
	},
	actions: {
		// 获取购物车列表
		async getShopCartList() {
			this.isLoading = true
			try {
				const { data } = await apiGetShopCartList()
				this.list = data.list || []
				return Promise.resolve('ok');
			} catch (error) {
				showToast(error.msg);
				console.log(error, 'error');
			} finally {
				this.isLoading = false;
			}
		},
		// 删除购物车商品
		async deleteShopCartList(shopCartIds) {
			if (!shopCartIds || shopCartIds.length === 0) return;
			this.isDeleteLoading = true;
			this.error = null;
			try {
				await deleteBatch({ shop_cart_ids: shopCartIds });
				// 如果接口返回成功但没有实际数据，可以省略下面这行
				// this.list = this.list.filter(item => !shopCartIds.includes(item.id));
			} catch (error) {
				this.error = error.message || '删除失败';
				throw error; // 抛出错误
			} finally {
				this.isDeleteLoading = false;
			}
		},
		// 减少商品数量
		minusChange(item) {
			// 给他一定的延时，不让用户连续点击操作
			if (item.number > 1) {
				uni.showLoading({
					title: "加载中...",
					mask: true
				})
				setTimeout(() => {
					item.number--;
					uni.hideLoading()
				}, 200)
			}
		},
		// 增加商品数量
		plusChange(item) {
			// 给他一定的延时，不让用户连续点击操作
			uni.showLoading({
				title: "加载中...",
				mask: true
			})
			setTimeout(() => {
				item.number++;
				uni.hideLoading()
			}, 200)
		},
		// 切换单个商品的选中状态
		toggleSelectItem(itemId) {
			if (this.selectedIds.has(itemId)) {
				this.selectedIds.delete(itemId);
			} else {
				this.selectedIds.add(itemId);
			}
		},

		// 全选/取消全选
		toggleSelectAll(isAllSelected) {
			if (isAllSelected) {
				this.selectedIds.clear();
			} else {
				this.selectedIds = new Set(this.list.map(item => item.id));
			}
		},
		// 初始化购物车列表后，同步选中状态
		initSelectedIds() {
			// 如果列表为空，清空选中状态
			if (this.list.length === 0) {
				this.selectedIds.clear();
				return;
			}
			// 过滤掉不存在的商品ID
			this.selectedIds = new Set(
				[...this.selectedIds].filter(id => this.list.some(item => item.id === id))
			);
		},
		async deleteItem(productId, specId) {
			const itemIndex = this.list.findIndex(
				item => item.product.id === productId && item.productSpec.id === specId
			);
			if (itemIndex === -1) return;
			const item = this.list[itemIndex];
			// 先更新（先删除视图，失败时回滚）
			this.list.splice(itemIndex, 1);
			this.selectedIds.delete(item.id);
			try {
				await this.deleteShopCartList([item.id]);
			} catch (error) {
				// 回滚操作
				this.list.splice(itemIndex, 0, item);
				this.selectedIds.add(item.id);
				throw error; // 重新抛出错误以便组件处理
			}
		},
		// 批量删除选中的商品
		async deleteSelectedItems() {
			if (this.selectedIds.size === 0) return;
			const selectedIdsArray = Array.from(this.selectedIds);
			const selectedItems = this.list.filter(item => selectedIdsArray.includes(item.id));
			// 先更新
			this.list = this.list.filter(item => !selectedIdsArray.includes(item.id));
			const deletedIds = new Set(this.selectedIds);
			this.selectedIds.clear();
			try {
				await this.deleteShopCartList(selectedIdsArray);
			} catch (error) {
				// 回滚操作
				this.list.push(...selectedItems);
				this.selectedIds = deletedIds;
				throw error;
			}
		},
	},
})

export default useCartStore